<template>
  <div class="preport">
    <div class="search-box">
      <Form inline :label-width="80">
        <FormItem label="ID">
          <Input type="text" v-model="id" placeholder="ID">
          </Input>
        </FormItem>
        <FormItem label="检索条件">
          <Select v-model="paramName" style="width:100px" clearable>
            <Option value="itemCode">项目编码</Option>
            <Option value="itemName">项目名称</Option>
          </Select>
          <Input type="text" v-model="value" placeholder="" style="width:200px">
          </Input>
        </FormItem>
        <FormItem>
        <Button type="primary" @click="doSearch">搜索</Button>
        <Button type="warning" @click="historySearch">历史版本</Button>
        </FormItem>
      </Form>
    </div>
    <div class="opt">
      <Button type="primary" @click="doSearch">刷新</Button>
      <Button type="success" @click="add">新增</Button>
    </div>
    <div class="data-table">
      <Table border :columns="columns" :data="tableData" size="small" :loading="tableLoading"></Table>
    </div>

    <Drawer
      :title="title"
      v-model="showEdit"
      width="720"
      :mask-closable="false"
      :styles="styles"
    >
      <Form :model="editData" :label-width="80">
        <FormItem label="文档号" prop="identifier">
          <Input v-model="editData.identifier"/>
        </FormItem>
        <FormItem label="文档类型" prop="docTypeCode">
          <CommonSelect v-model="editData.docTypeCode" :code.sync="editData.docTypeCode"
                        :name.sync="editData.docTypeName" :data-options="docTypeDict">
          </CommonSelect>
        </FormItem>
        <FormItem label="文档名称" prop="docTitle">
          <Input v-model="editData.docTitle"/>
        </FormItem>
        <FormItem label="文档作者" prop="author">
          <Input v-model="editData.author"/>
        </FormItem>
        <FormItem label="患者" prop="patientName">
          <Input v-model="editData.patientName"/>
        </FormItem>
        <FormItem label="性别" prop="sex">
          <Select v-model="editData.sex">
            <Option value="male">男</Option>
            <Option value="female">女</Option>
            <Option value="other">其他</Option>
            <Option value="unknown">未知</Option>
          </Select>
        </FormItem>
        <FormItem label="电话" prop="telephone">
          <Input v-model="editData.telephone"/>
        </FormItem>
        <FormItem label="出生日期" prop="birthDate">
          <DatePicker type="date" v-model="editData.birthDate"/>
        </FormItem>
        <FormItem label="家庭地址" prop="homeAddr">
          <Input v-model="editData.homeAddr"/>
        </FormItem>
        <FormItem label="就诊类型" prop="visitTypeCode">
          <CommonSelect v-model="editData.visitTypeCode" :code.sync="editData.visitTypeCode"
                        :name.sync="editData.visitTypeName" :data-options="visitTypeDict">
          </CommonSelect>
        </FormItem>
        <FormItem label="入院时间" prop="visitTime">
          <DatePicker type="datetime" v-model="editData.visitTime"/>
        </FormItem>
        <FormItem label="出院时间" prop="dischargeTime">
          <DatePicker type="datetime" v-model="editData.dischargeTime"/>
        </FormItem>
        <FormItem label="报告名称" prop="text">
          <Input v-model="editData.text"/>
        </FormItem>
        <FormItem label="报告时间" prop="reportDate">
          <DatePicker type="datetime" v-model="editData.reportDate"/>
        </FormItem>
        <FormItem label="检查时间" prop="effectiveDateTime">
          <DatePicker type="datetime" v-model="editData.effectiveDateTime"/>
        </FormItem>
        <FormItem label="检查类型" prop="categoryCode">
          <CommonSelect v-model="editData.categoryCode" :code.sync="editData.categoryCode"
                        :name.sync="editData.categoryName" :data-options="categoryCodeDict">
          </CommonSelect>
        </FormItem>
        <FormItem label="检查项目" prop="code">
          <CommonSelect v-model="editData.code" :code.sync="editData.code"
                        :name.sync="editData.display" :data-options="labItemDict">
          </CommonSelect>
        </FormItem>
        <FormItem label="检查部位" prop="bodySiteCode">
          <CommonSelect v-model="editData.bodySiteCode" :code.sync="editData.bodySiteCode"
                        :name.sync="editData.bodySiteName" :data-options="bodySiteDict">
          </CommonSelect>
        </FormItem>
        <FormItem label="检查方法" prop="methodCode">
          <CommonSelect v-model="editData.methodCode" :code.sync="editData.methodCode"
                        :name.sync="editData.methodName" :data-options="methodDict">
          </CommonSelect>
        </FormItem>
        <FormItem label="检查医生" prop="tester">
          <Input v-model="editData.tester"/>
        </FormItem>
        <FormItem label="检查设备" prop="device">
          <Input v-model="editData.device"/>
        </FormItem>
        <FormItem label="结果" prop="result">
          <Input v-model="editData.result"/>
        </FormItem>
      </Form>

      <div class="demo-drawer-footer">
        <Button style="margin-right: 8px" type="primary" @click="onSubmit">确定</Button>
        <Button type="error" @click="showEdit = false">取消</Button>
      </div>
    </Drawer>
  </div>
</template>

<script>
  import CommonSelect from "../../../components/select/commonSelect";

  export default {
    name: "preport",
    components: { CommonSelect},
    computed: {
      tableData() {
        let jData = [];


        this.$store.state.bundle.bundleList.forEach((entry, i) => {

          let re = entry.resource;


          if (entry.resource &&   re.hasOwnProperty('entry') && re.total)
            return;

          let
            docTypeCode,
            docTypeName,
            docTitle,
            reportDate,
            code,
            display,
            text,
            bodySiteName,
            bodySiteCode,
            patientName,
            effectiveDateTime,
            birthDate,
            telephone,
            homeAddr,
            sex,
            visitTypeCode,
            visitTypeName,
            visitTime,
            dischargeTime,
            tester,
            device,
            result,
            categoryCode,
          categoryName,
             methodCode,
            methodName,
            author;

          let resUrl = re.id.myStringValue;
          let id = re.id.myUnqualifiedId;
          let versionId = re.meta.versionId ? re.meta.versionId.myStringValue : "";
          let identifier = (re.identifier && re.identifier.value) ? re.identifier.value.myStringValue : "";


          let subId = 0;

            if(!re.entry){

              return;
            }
         re.entry.forEach(o => {
            debugger;
            if (o.request) {

              let type = o.request.url.myStringValue;
              let res = o.resource;
              switch (type) {
                case "Composition":
                  author = (res.author && res.author[0].display) ? res.author[0].display.myStringValue : "";
                  docTitle = res.title ? res.title.myStringValue : '';
                  docTypeCode = (res.type && res.type.coding && res.type.coding[0].code) ?
                    res.type.coding[0].code.myStringValue : "";
                  docTypeName = (res.type && res.type.text) ? res.type.text.myStringValue : "";
                  reportDate= (res.date && res.date.myStringValue) ? res.date.myStringValue:"";
                  break;
                case "Patient":
                  patientName = (res.name && res.name[0].text) ? res.name[0].text.myStringValue : "";
                  telephone = (res.telecom && res.telecom[0].value) ? res.telecom[0].value.myStringValue : "";
                  sex = res.gender ? res.gender.myStringValue : "";
                  birthDate = res.birthDate ? res.birthDate.myStringValue : "";
                  homeAddr = (res.address && res.address[0].line[0]) ? res.address[0].line[0].myStringValue : "";
                  break;
                case "Encounter":
                  visitTypeCode = res.class_ ? (res.class_.code ? res.class_.code.myStringValue : '') : '';
                  visitTypeName = res.class_ ? (res.class_.display ? res.class_.display.myStringValue : '') : '';
                  visitTime = res.period ? (res.period.start ? res.period.start.myStringValue : '') : '';
                  dischargeTime = res.period ? (res.period.end ? res.period.end.myStringValue : '') : '';
                  break;
                case "Observation":
                  if (res.value) {

                    bodySiteName=(res.bodySite && res.bodySite.text) ? res.bodySite.text.myStringValue:"";
                    bodySiteCode=(res.bodySite && res.bodySite.coding[0] && res.bodySite.coding[0].code) ? res.bodySite.coding[0].code.myStringValue:"";

                    categoryName=(res.category&&res.category[0] && res.category[0].coding && res.category[0].coding[0] && res.category[0].coding[0].display) ? res.category[0].coding[0].display.myStringValue:"";
                    categoryCode=(res.category&&res.category[0] && res.category[0].coding && res.category[0].coding[0] && res.category[0].coding[0].code) ? res.category[0].coding[0].code.myStringValue:"";


                    tester = res.performer && res.performer[0].display ? res.performer[0].display.myStringValue : '';

                    code = (res.code && res.code.coding && res.code.coding[0]) ? res.code.coding[0].code.myStringValue : "";
                    display = (res.code && res.code.coding && res.code.coding[0] && res.code.coding[0].display)? res.code.coding[0].display.myStringValue : "";

                   effectiveDateTime=(res.effective) ? res.effective.myStringValue : "";
                    device=(res.device && res.device.display) ? res.device.display.myStringValue:"";
                    text = (res.code && res.code.text) ? res.code.text.myStringValue : "";

                    methodCode=(res.method && res.method.coding && res.method.coding[0].code) ? res.method.coding[0].code.myStringValue:"";
                     methodName=(res.method && res.method.text) ? res.method.text.myStringValue:"";
                    result=res.value.myStringValue;
                  } else {
                    code = (res.code && res.code.coding && res.code.coding[0]) ? res.code.coding[0].code.myStringValue : "";
                    display = (res.code && res.code.coding && res.code.coding[0]) ? res.code.coding[0].display.myStringValue : "";
                    text = (res.code && res.code.text) ? res.code.text.myStringValue : "";
                  }

                  break;

              }
            } else if (o.fullUrl) {
              let res = o.resource;
              let exp = new RegExp(this.$store.state.base.fhirServer + '(\\S*)' + '/');
              let type =(o.fullUrl.myStringValue.match(exp)) ?  o.fullUrl.myStringValue.match(exp)[1].replace("/", ""):"";
              switch (type) {
                case "Composition":
                  author = (res.author && res.author[0].display) ? res.author[0].display.myStringValue : "";
                  docTitle = res.title ? res.title.myStringValue : '';
                  docTypeCode = (res.type && res.type.coding && res.type.coding[0].code) ?
                    res.type.coding[0].code.myStringValue : "";
                  docTypeName = (res.type && res.type.text) ? res.type.text.myStringValue : "";
                  reportDate= (res.date && res.date.myStringValue) ? res.date.myStringValue:"";
                  break;
                case "Patient":
                  patientName = (res.name && res.name[0].text) ? res.name[0].text.myStringValue : "";
                  telephone = (res.telecom && res.telecom[0].value) ? res.telecom[0].value.myStringValue : "";
                  sex = res.gender ? res.gender.myStringValue : "";
                  birthDate = res.birthDate ? res.birthDate.myStringValue : "";
                  homeAddr = (res.address && res.address[0].line[0]) ? res.address[0].line[0].myStringValue : "";
                  break;
                case "Encounter":
                  visitTypeCode = res.class_ ? (res.class_.code ? res.class_.code.myStringValue : '') : '';
                  visitTypeName = res.class_ ? (res.class_.display ? res.class_.display.myStringValue : '') : '';
                  visitTime = res.period ? (res.period.start ? res.period.start.myStringValue : '') : '';
                  dischargeTime = res.period ? (res.period.end ? res.period.end.myStringValue : '') : '';
                  break;
                case "Observation":
                  if (res.value) {

                    bodySiteName=(res.bodySite && res.bodySite.text) ? res.bodySite.text.myStringValue:"";
                    bodySiteCode=(res.bodySite && res.bodySite.coding[0] && res.bodySite.coding[0].code) ? res.bodySite.coding[0].code.myStringValue:"";

                    categoryName=(res.category&&res.category[0] && res.category[0].coding && res.category[0].coding[0] && res.category[0].coding[0].display) ? res.category[0].coding[0].display.myStringValue:"";
                    categoryCode=(res.category&&res.category[0] && res.category[0].coding && res.category[0].coding[0] && res.category[0].coding[0].code) ? res.category[0].coding[0].code.myStringValue:"";


                    tester = res.performer && res.performer[0].display ? res.performer[0].display.myStringValue : '';

                    code = (res.code && res.code.coding && res.code.coding[0]) ? res.code.coding[0].code.myStringValue : "";
                    display = (res.code && res.code.coding && res.code.coding[0] && res.code.coding[0].display)? res.code.coding[0].display.myStringValue : "";


                    effectiveDateTime=(res.effective) ? res.effective.myStringValue : "";
                    device=(res.device && res.device.display) ? res.device.display.myStringValue:"";
                    text = (res.code && res.code.text) ? res.code.text.myStringValue : "";

                    methodCode=(res.method && res.method.coding && res.method.coding[0].code) ? res.method.coding[0].code.myStringValue:"";
                    methodName=(res.method && res.method.text) ? res.method.text.myStringValue:"";
                    result=res.value.myStringValue;
                  } else {
                    code = (res.code && res.code.coding && res.code.coding[0]) ? res.code.coding[0].code.myStringValue : "";
                    display = (res.code && res.code.coding && res.code.coding[0]) ? res.code.coding[0].display.myStringValue : "";
                    text = (res.code && res.code.text) ? res.code.text.myStringValue : "";
                  }

                  break;

              }
            }
          });
          jData.push({
            url: resUrl,
            id: id,
            versionId: versionId,
            identifier: identifier,
            docTypeCode: docTypeCode,
            docTypeName: docTypeName,
            reportDate:reportDate,
            docTitle: docTitle,
            code: code,
            display: display,
            text: text,
            bodySiteName: bodySiteName,
            bodySiteCode:bodySiteCode,
            methodCode:methodCode,
            methodName:methodName,
            patientName: patientName,
            birthDate: birthDate,
            telephone: telephone,
            homeAddr: homeAddr,
            sex: sex,
            visitTypeCode: visitTypeCode,
            visitTypeName: visitTypeName,
            visitTime: visitTime,
            dischargeTime: dischargeTime,
            tester: tester,
            device: device,
            categoryCode:categoryCode,
            effectiveDateTime:effectiveDateTime,
          categoryName:categoryName,
            author: author,
            result: result
          })

        });
        return jData;
      }
    },
    data() {
      return {
        type: 'Bundle',
        SEQ: 0,
        id: null,
        paramName: null,
        value: null,
        tableLoading: false,
        showEdit: false,
        isUpdate: false,
        title: '',
        editData: {},
        visitTypeDict: [{code: 'IMP', name: '住院'}],
        docTypeDict: [{code: '28655-1', name: '检查报告'}],
        labItemDict: [{code: '80859-2', name: '心脏彩色多普勒超声'}],
        bodySiteDict:[{code: '71341001:272741003=2643008', name: '心脏'}],
        methodDict:[{code: '71341001:272741003=2643008', name: '正位'}],
        categoryCodeDict:[{code: 'B超', name: 'B超'}],
        editResult: true,
        styles: {
          height: 'calc(100% - 55px)',
          overflow: 'auto',
          paddingBottom: '53px',
          position: 'static'
        },
        columns: [

          {
            title: 'ID',
            key: 'id'
          },
          {
            title: '版本',
            key: 'versionId'
          },
          {
            title: '文档号',
            key: 'identifier'
          },
          {
            title: '文档类型名称',
            key: 'docTypeName'
          },
          {
            title: '文档名称',
            key: 'docTitle'
          },
          {
            title: '文档作者',
            key: 'author'
          },
          {
            title: '患者',
            key: 'patientName'
          },
          {
            title: '就诊类型',
            key: 'visitTypeName'
          },
          {
            title: '就诊（入院）时间',
            key: 'visitTime'
          },
          {
            title: '出院时间',
            key: 'dischargeTime'
          },
          {
            title: '项目代码',
            key: 'code'
          },
          {
            title: '项目名称',
            key: 'display'
          },
          {
            title: '报告名称',
            key: 'text'
          },
          {

            title: '报告结果',
           width:250,
            key: 'result',



          },
          {
            title: '报告时间',
            key: 'reportDate'
          },
          {
            title: '检查时间',
            key: 'effectiveDateTime'
          },
          {
            title: '检查者',
            key: 'tester'
          },
          {
            title: '部位',
            key: 'bodySiteName'
          },
          {
            title: '检查设备',
            key: 'device'
          },
          {
            title: "操作",
            width: 120,
            type: "render",
            render: (h, params) => {
              return h('div', {
                class: 'btn-wrap'
              }, [
                h('a', {
                  on: {
                    click: () => {
                      this.update(params.row)
                    }
                  }
                }, '编辑'),
                h('Divider', {
                  props: {type: 'vertical'},
                }),
                h('a', {
                  on: {
                    click: () => {
                      this.remove(params.row)
                    }
                  }
                }, '删除'),
              ])
            }
          }
        ]
      }
    },
    created() {
      this.doSearch();
    },
    methods: {
      changeItem(item) {
        console.log(item);
      },
      doSearch() {
        this.tableLoading = true;
        this.$store.dispatch('getBundleList', {
          type: this.type,
          id: this.id,
          paramName: this.paramName,
          value: this.value,
        }).then(() => {
          this.tableLoading = false;
        }).catch(res => {
          this.$Notice.error({
            title: re.error,
            desc: re.message
          });
          this.tableLoading = false;
        })
      },
      historySearch() {
        if (!this.id) {
          this.$Message.error('请输入ID');
          return;
        }
        this.tableLoading = true;
        this.$store.dispatch('getHistoryBundleList', {
          type: this.type,
          id: this.id,
        }).then(() => {
          this.tableLoading = false;
        })
      },
      add() {
        this.editData = {
          identifier: "doc_100000" + (++this.SEQ),
          docTypeCode: '28655-1',
          docTypeName: '检查报告',
          docTitle: '检查报告',
          code: "80859-2",
          display: "心脏彩色多普勒超声",
          text: "心脏彩色多普勒超声报告",
          bodySiteName: "部位",
          bodySiteCode:"71341001:272741003=2643008",
          methodCode:"71341001:272741003=2643008",
          methodName:"正位",
          categoryCode:"B超",
          categoryName:"B超",
          patientName: '张三',
          birthDate: "2003-01-12",
          telephone: "13800138000",
          homeAddr: "北京市东城区景山前街4号",
          sex: "male",
          visitTypeCode: 'IMP',
          visitTypeName: '住院',
          visitTime: '2018-10-28 12:46:41',
          dischargeTime: '2018-11-01 12:46:48',
          effectiveDateTime:'2018-11-01 13:46:48',
          reportDate:'2018-11-01 15:46:48',
          tester: "李四",
          device: "彩色多普勒超声",
          author: '宋健',
          result:'M 型/二维测量和计算\n' +
            '主肺动脉内径: 2.1 厘米 室间隔舒张末期\n' +
            '厚度: 0.85 厘米 射血分数(Teich): 66.3%\n' +
            '多普勒测试和计算\n' +
            '主动脉瓣上最大流速: 141.5 厘米/秒 二\n' +
            '尖瓣 E 峰速度: 82.8 厘米/秒\n' +
            '大血管 主动脉根部内径正常。肺动脉主干内径\n' +
            '正常。\n' +
            '心房 左房扩大。右房内径正常。'

        };
        this.showEdit = true;
        this.isUpdate = false;
        this.title = '新增检查报告';
      },
      update(row) {
        this.editData = JSON.parse(JSON.stringify(row));
        this.showEdit = true;
        this.isUpdate = true;
        this.title = '更新检查报告';
      },
      remove(row) {
        this.$store.dispatch('deleteBundle', {
          type: this.type,
          id: row.id
        }).then(() => {
          this.$Message.success('删除成功');
          this.id = row.id;
          this.doSearch();
        });
      },
      onSubmit() {
        if (this.isUpdate) {
          this.$store.dispatch('updateBundle', Object.assign({type: this.type}, this.editData)).then(() => {
            this.$Message.success('更新成功');
            this.showEdit = false;
            this.id = this.editData.id;
            this.doSearch();
          });
        } else {
          this.$store.dispatch('createBundle', Object.assign({type: this.type}, this.editData)).then((res) => {
            this.$Message.success('新增成功');
            this.showEdit = false;
            this.id = res.data.myId.myUnqualifiedId;
            this.doSearch();
          });
        }
      }
    }
  }
</script>


<style scoped>
  .data-table {
    margin-top: 10px;
  }

  .demo-drawer-footer {
    width: 100%;
    position: absolute;
    bottom: 0;
    left: 0;
    border-top: 1px solid #e8e8e8;
    padding: 10px 16px;
    text-align: right;
    background: #fff;
  }
</style>

